/**
 * 性能监控装饰器
 * 用于监控方法执行时间
 */
export function Performance() {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
      const start = new Date().getTime();
      const result = originalMethod.apply(this, args);
      const end = new Date().getTime();
      console.info(`${propertyKey} execution time: ${end - start}ms`);
      return result;
    };
    return descriptor;
  };
}

/**
 * 错误处理装饰器
 * 统一处理方法执行时的错误
 */
export function ErrorHandler() {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
      try {
        return originalMethod.apply(this, args);
      } catch (error) {
        console.error(`Error in ${propertyKey}:`, error);
        throw error;
      }
    };
    return descriptor;
  };
}

/**
 * 防抖装饰器
 * @param delay 延迟时间，默认300ms
 */
export function Debounce(delay: number = 300) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    let timer: number | null = null;
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
      if (timer !== null) {
        clearTimeout(timer);
      }
      timer = setTimeout(() => {
        originalMethod.apply(this, args);
      }, delay);
    };
    return descriptor;
  };
}

/**
 * 节流装饰器
 * @param delay 延迟时间，默认300ms
 */
export function Throttle(delay: number = 300) {
  return function (target: any, propertyKey: string, descriptor: PropertyDescriptor) {
    let lastTime = 0;
    const originalMethod = descriptor.value;
    descriptor.value = function (...args: any[]) {
      const now = new Date().getTime();
      if (now - lastTime >= delay) {
        originalMethod.apply(this, args);
        lastTime = now;
      }
    };
    return descriptor;
  };
}
